/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import dto.ProductDTO;
import tool.CommonConstants;
import tool.DBUtilities;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.buf.TimeStamp;

/**
 *
 * @author DH
 */
public class ProductProcessServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");

            if (action.equals("Delete")) {
                String productId = request.getParameter("productId");
                Connection con = null;
                try {
                    con = DBUtilities.createConnection();
                    String deleteQuery = "UPDATE [Product] SET [isActive] = '0' WHERE [id] = ?";
                    PreparedStatement ps = con.prepareStatement(deleteQuery);
                    ps.setString(1, productId);
                    ps.executeUpdate();
                    response.sendRedirect(CommonConstants.STARTUP_SERVLET);
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                } finally {
                    if (con != null) {
                        try {
                            con.close();
                        } catch (SQLException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            } else if (action.equals("Add")) {
                Connection con = null;
                try {
                    con = DBUtilities.createConnection();
                    String productName = request.getParameter("txtProductName");
                    String description = request.getParameter("txtDescription");
                    String category = request.getParameter("txtCategoryId");
                    String price = request.getParameter("txtPrice");
                    String imagePath = request.getParameter("txtImagePath");
                    Date addDate = new Date();
                    String addQuery = "INSERT [Product] ([productName], [productDescription], [productCategoryId], [price]"
                            + ", [imagePath], [addDate], [isActive]) VALUES (?, ?, ?, ?, ?, ?, '1')";
                    PreparedStatement ps = con.prepareStatement(addQuery);
                    ps.setString(1, productName);
                    ps.setString(2, description);
                    ps.setInt(3, Integer.parseInt(category));
                    ps.setInt(4, Integer.parseInt(price));
                    ps.setString(5, imagePath);
                    ps.setTimestamp(6, new Timestamp(addDate.getTime()));
                    ps.executeUpdate();
                    String url = CommonConstants.PRODUCT_PROCESS_SERVLET + "?action=manage";
                    response.sendRedirect(url);

                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                } finally {
                    if (con != null) {
                        try {
                            con.close();
                        } catch (SQLException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            } else if (action.equals("manage")) {
                Connection con = null;
                ResultSet rs = null;
                try {
                    con = DBUtilities.createConnection();

                    String query = "SELECT * FROM [Product] WHERE [isActive] = '1'";
                    PreparedStatement ps = con.prepareStatement(query);
                    rs = ps.executeQuery();

                    List prodList = new ArrayList();
                    ProductDTO prod = null;

                    if (rs != null) {
                        while (rs.next()) {
                            int id = rs.getInt("id");
                            String productName = rs.getString("productName");
                            String productDescription = rs.getString("productDescription");
                            int productCategoryId = rs.getInt("productCategoryId");
                            int price = rs.getInt("price");
                            String imagePath = rs.getString("imagePath");
                            Date addDate = rs.getTimestamp("addDate");
                            prod = new ProductDTO(id, productName, productDescription, productCategoryId, price, imagePath, addDate, true);
                            prodList.add(prod);
                        }
                    }

                    HttpSession ss = request.getSession();
                    ss.setAttribute("PROD2", prodList);
                    response.sendRedirect(CommonConstants.MANAGE_PRODUCT_PAGE);

                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }

            }


        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
